<script setup>
// ================ 数据模型定义  start ================

// 定义搜索表单数据模型
// 定义搜索表单数据模型
import Pagination from "@/components/Pagination/index.vue";
import {
    addCategoryBrand,
    deleteCategoryBrand,
    getBrandAll,
    getCategoryBrand,
    listCategoryBrand,
    updateCategoryBrand
} from "@/api/product/categoryBrand.js";
import {getTreeSelect} from "@/api/product/category.js";

// 定义表格数据模型
const categoryBrandList = ref([]);
// 定义列表总记录数模型
const total = ref(0)
// 加载数据时显示的动效控制模型
const loading = ref(true)
// 定义隐藏搜索控制模型
const showSearch = ref(true)
// 定义品牌数据模型
const brandList = ref([]);
// 新增与修改弹出层控制模型
const open = ref(false);
// 新增与修改弹出层标题模型
const title = ref("");
// 定义批量操作id列表模型
const ids = ref([]);
// 定义单选按钮控制模型
const single = ref(true);
// 定义删除按钮控制模型
const multiple = ref(true);

// 处理分类change事件
const queryCategoryIdList = ref([]);
const handleCategoryChange = () => {
    if (queryCategoryIdList.value.length === 3) {
        queryParams.value.categoryId = queryCategoryIdList.value[2];
    }
}

// 多选框选中数据change事件
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.id)
    single.value = selection.length !== 1;
    multiple.value = !selection.length;
}

// 三级分类
const props = {
    lazy: true,
    value: 'id',
    label: 'name',
    leaf: 'leaf',
    async lazyLoad(node, resolve) {   // 加载数据的方法
        const {level} = node;
        if (typeof node.value === 'undefined') {
            node.value = 0;
        }
        const {code, data, message} = await getTreeSelect(node.value)
        data.forEach(function (item) {
            item.leaf = !item.hasChildren;
        })
        resolve(data)  // 返回数据
    }
};

const categoryProps = ref(props)

const {proxy} = getCurrentInstance()

// 定义数据模型
const data = reactive({

    // 定义用于搜索的数据模型
    queryParams: {
        // 分页条件
        pageNum: 1,
        pageSize: 10,
        // 品牌id
        brandId: null,
        // 分类id
        categoryId: null,
    },
    form: {},
    rules: {
        categoryIdList: [
            {required: true, message: "分类不能为空", trigger: "blur"}
        ],
        brandId: [
            {required: true, message: "品牌不能为空", trigger: "blur"}
        ]
    }
})

// 转换数据模型
const {queryParams, form, rules} = toRefs(data)

/* 查询分类品牌列表 */
function getList() {
    loading.value = true
    listCategoryBrand(queryParams.value).then(response => {
        categoryBrandList.value = response.rows;
        total.value = response.total;
        loading.value = false
    })
}

/* 获取全部品牌数据 */
function getBrandAllList() {
    getBrandAll().then(response => {
        brandList.value = response.data;
    })
}

/* 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}

/* 重置按钮操作 */
function resetQuery() {
    queryCategoryIdList.value = [];
    proxy.resetForm("queryRef");
    queryParams.value.categoryId = null;
    queryParams.value.brandId = null;
    handleQuery();
}

/* 表单重置 */
function reset() {
    form.value = {
        id: null,
        brandId: null,
        categoryId: null,
        categoryIdList: []
    }
    proxy.resetForm("categoryBrandRef")
}

/* 新增按钮操作 */
function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加分类品牌";
}

/* 提交确定按钮 */
function submitForm() {
    proxy.$refs["categoryBrandRef"].validate(valid => {
        debugger
        if (valid) {
            form.value.categoryId = form.value.categoryIdList[2]
            if (form.value.id !== null) {
                updateCategoryBrand(form.value).then((response) => {
                    proxy.$modal.msgSuccess("修改成功");
                    open.value = false;
                    getList();
                })
            } else {
                addCategoryBrand(form.value).then((response) => {
                    proxy.$modal.msgSuccess("新增成功");
                    open.value = false;
                    getList();
                })
            }
        }
    })
}

/* 取消按钮 */
function cancel() {
    open.value = false;
    reset()
}

/* 修改按钮 */
function handleUpdate(row) {
    reset();
    const _id = row.id || ids.value;
    getCategoryBrand(_id).then(response => {
        form.value = response.data;
        open.value = true;
        title.value = "修改分类品牌";
    })
}

/* 删除按钮 */
function handleDelete(row) {
    const _ids = row.id || ids.value;
    proxy.$modal.confirm('是否确认删除分类品牌编号为"' + _ids + '"的数据项?').then(function () {
        return deleteCategoryBrand(_ids);
    }).then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {
    })
}

// 挂载自动调用
getList()
getBrandAllList()

// ================   数据模型定义 end ================
</script>

<template>
    <div class="app-container">

        <!-- Form 表单组件 - Form 表单 -->
        <el-form v-show="showSearch" ref="queryRef" :inline="true" :model="queryParams" label-width="68px">
            <el-form-item label="分类">
                <!-- Form 表单组件 - Cascader 级联选择器 -->
                <el-cascader
                    v-model="queryCategoryIdList"
                    :props="categoryProps"
                    style="width: 100%"
                    @change="handleCategoryChange"
                />
            </el-form-item>

            <el-form-item label="品牌">
                <!-- Form 表单组件 - Select 选择器 -->
                <el-select
                    v-model="queryParams.brandId"
                    class="m-2"
                    placeholder="选择品牌"
                    style="width: 100%"
                >
                    <el-option
                        v-for="item in brandList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
                <el-button id="reset-all" icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- Basic 基础组件 - Layout 布局 -->
        <el-row :gutter="10" class="mb8">
            <el-col span="1.5">
                <!-- Basic 基础组件 - Button 按钮-->
                <el-button icon="Plus" plain type="primary" @click="handleAdd">新增</el-button>
            </el-col>
            <el-col span="1.5">
                <el-button :disabled="single" icon="Edit" plain type="success" @click="handleUpdate">修改</el-button>
            </el-col>
            <el-col span="1.5">
                <el-button :disabled="multiple" icon="Delete" plain type="danger" @click="handleDelete">删除</el-button>
            </el-col>
            <!-- 自定义的隐藏搜索和刷新组件 -->
            <right-toolbar v-model:show-search="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <!-- Data 数据展示 - Table 表格 -->
        <el-table v-loading="loading" :data="categoryBrandList" @selection-change="handleSelectionChange">
            <el-table-column align="center" type="selection" width="55"/>
            <el-table-column align="center" label="分类名称" prop="categoryName" width="200"/>
            <el-table-column align="center" label="品牌名称" prop="brandName" width="200"/>
            <el-table-column #default="scope" align="center" label="品牌图标" prop="logo">
                <img :src="scope.row.logo" width="50"/>
            </el-table-column>
            <el-table-column align="center" label="创建时间" prop="createTime" width="200"/>
            <el-table-column align="center" label="操作">
                <template #default="scope">
                    <el-button icon="Edit" link type="primary" @click="handleUpdate(scope.row)">修改</el-button>
                    <el-button icon="Delete" link type="primary" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 自定义的分页条组件 -->
        <pagination
            v-show="total>0"
            v-model:limit="queryParams.pageSize"
            v-model:page="queryParams.pageNum"
            :total="total"
            @pagination="getList"
        />

        <!-- Dialog 对话框 -->
        <el-dialog v-model="open" :rules="rules" :title="title" append-to-body width="500px">
            <el-form ref="categoryBrandRef" :model="form" label-width="80px">
                <el-form-item label="分类" prop="categoryIdList">
                    <el-cascader
                        v-model="form.categoryIdList"
                        :props="categoryProps"
                    />
                </el-form-item>
                <el-form-item label="品牌" prop="brandId">
                    <el-select
                        v-model="form.brandId"
                        class="m-2"
                        placeholder="选择品牌"
                    >
                        <el-option
                            v-for="item in brandList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>

<style lang="scss" scoped>

</style>